package serialization;

/*
Compile client and server and then start server as follows:

$ java GreetingServer 6066
Waiting for client on port 6066...
Check client program as follows:

$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!
*/
import java.net.*;
import java.util.ArrayList;
import java.io.*;

public class StudentServer extends Thread
{
   private ServerSocket serverSocket;
	
   public StudentServer(int port) throws IOException
   {
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(20000);//20 seconds
   }

   public void run()
   {
      while(true)
      {
         try
         {
            System.out.println("Server: Waiting for client on port " + serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            System.out.println("Server: Just connected to " + server.getRemoteSocketAddress());
            
            DataInputStream in = new DataInputStream(server.getInputStream());
            System.out.println("Server gets the message from client: "+in.readUTF());
            
            DataOutputStream out = new DataOutputStream(server.getOutputStream());
            out.writeUTF("Sure, here is the object.");
            
            ObjectOutputStream objectOut = new ObjectOutputStream(server.getOutputStream());
            ArrayList<Student> students = new ArrayList<Student>();
     	    Student s1 = new Student(33333333,"Carl");
    	    Student s2 = new Student(44444444,"Denny");
    	    students.add(s1);
    	    students.add(s2);
            objectOut.writeObject(students);
            
            server.close();
         }catch(SocketTimeoutException s)
         {
            System.out.println("Server: Socket timed out!");
            break;
         }catch(IOException e)
         {
            e.printStackTrace();
            break;
         }
      }
   }
   public static void main(String [] args)
   {
      int port = Integer.parseInt("6066");
      try
      {
         Thread t = new StudentServer(port);
         t.start();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}